/** 
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 * 
 *BaseShareManageController
 * 共享管理
 * 
 * 修改纪录
 * 2020-08-27 版本：1.0 donghang 创建。
 * @version 版本：1.0
 * @author 作者：donghang
 * 创建日期：2020-08-27
 */

package com.topscomm.base.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.topscomm.base.controller.auto.BaseShareManageControllerAuto;
import com.topscomm.base.pojo.BaseShareManageEntity;
import com.topscomm.base.service.impl.BaseCboUserExtendService;
import com.topscomm.base.service.impl.BaseTeamInfoService;
import com.topscomm.cbo.service.impl.CboUserService;
import com.topscomm.pub.util.BaseUtil;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import com.topscomm.pub.vo.ResponseResult;

/**
 * @author: donghang
 * @date: 2020-08-27
 * @description:共享管理Controller
 * @modify:
 */
@RestController
@RequestMapping("base/shareManage")
public class BaseShareManageController extends BaseShareManageControllerAuto implements IBaseShareManageController {

	@Autowired
	BaseCboUserExtendService baseCboUserExtendService;

	@Autowired
	BaseTeamInfoService baseTeamInfoService;
	@Autowired
	CboUserService cboUserService;

	/**
	 * @author: donghang
	 * @date: 2020-08-27
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" 1=1 ");
		if (paraMap.containsKey("qry_name")) {
			String value = paraMap.get("qry_name").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and name like '%{0}%' ", value);
		}
		if (paraMap.containsKey("qry_code")) {
			String value = paraMap.get("qry_code").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and code = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_sharetype")) {
			String value = paraMap.get("qry_sharetype").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and sharetype = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_sourceid")) {
			String value = paraMap.get("qry_sourceid").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and sourceid = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_sourcetype")) {
			String value = paraMap.get("qry_sourcetype").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and sourcetype = '{0}' ", value);
		}
		return sql.toString();
	}

	/**
	 * @author: donghang
	 * @date: 2020-08-27
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/refList")
	public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
		return super.refList(paraMap);
	}

	/**
	 * @description: 查询选择的所有人员
	 * @param paraMap
	 * @return
	 * @author: jiangtao
	 * @date: 2020年9月2日下午7:49:11
	 * @modify:
	 */
	@GetMapping(value = "/searchMember")
	public ResponseResult<Object> searchMeetMember(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			Query query = new Query(paraMap);
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			// 查询当前共享管理的记录信息
			StringBufferProxy sql = new StringBufferProxy();
			sql.appendSingle(" 1= 1");
			sql.appendSingle(" and sourceid='{0}' and sourcetype='{1}' and sharetype='{2}'",
					paraMap.get("qry_sourceid"), paraMap.get("qry_sourcetype"), paraMap.get("qry_sharetype"));
			List<Map<String, Object>> baseShareManageList = this.service.queryMapByWhere(sql.toString(),
					"queryListByWhere");
			// 对比范围选择是否变化
			String sharedeptcodes = ConvertUtil.convertToString(paraMap.get("qry_sharedeptcodes"));
			String shareroleids = ConvertUtil.convertToString(paraMap.get("qry_shareroleids"));
			String shareteamids = ConvertUtil.convertToString(paraMap.get("qry_shareteamids"));
			String shareusercodes = ConvertUtil.convertToString(paraMap.get("qry_shareusercodes"));
			boolean isQuery = false;
			if (baseShareManageList.size() > 0) {
				Map<String, Object> oldShareManageMap = baseShareManageList.get(0);
				if (!ConvertUtil.convertToString(oldShareManageMap.get(BaseShareManageEntity.FieldSharedeptcodes))
						.equals(sharedeptcodes)
						|| !ConvertUtil.convertToString(oldShareManageMap.get(BaseShareManageEntity.FieldShareroleids))
								.equals(shareroleids)
						|| !ConvertUtil.convertToString(oldShareManageMap.get(BaseShareManageEntity.FieldShareteamids))
								.equals(shareteamids)
						|| !ConvertUtil
								.convertToString(oldShareManageMap.get(BaseShareManageEntity.FieldShareusercodes))
								.equals(shareusercodes)) {
					isQuery = true;
				}
			}
			String selectUserCodes = "";
			if (!isQuery && baseShareManageList.size() > 0) { // 范围没有变化直接取值
				selectUserCodes = ConvertUtil
						.convertToString(baseShareManageList.get(0).get(BaseShareManageEntity.FieldAllusercodes));
			} else { // 范围变化，重新计算人員
				List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
				if (paraMap.containsKey("qry_sharedeptcodes")) {
					if (!StringUtil.isEmpty(sharedeptcodes)) {
						List<Map<String, Object>> userList = baseCboUserExtendService
								.searchUsersByDeptCodes(sharedeptcodes);
						for (Map<String, Object> map : userList) {
							map.put("usercode", map.remove("code"));
							map.put("username", map.remove("name"));
						}
						resultList.addAll(userList);
					}
				}
				if (paraMap.containsKey("qry_shareroleids")) {
					if (!StringUtil.isEmpty(shareroleids)) {
						List<Map<String, Object>> userList = baseCboUserExtendService.searchUserByRoleIds(shareroleids);
						for (Map<String, Object> map : userList) {
							map.put("usercode", map.remove("code"));
							map.put("username", map.remove("name"));
						}
						resultList.addAll(userList);
					}
				}
				if (paraMap.containsKey("qry_shareteamids")) {
					if (!StringUtil.isEmpty(shareteamids)) {
						List<Map<String, Object>> userList = baseTeamInfoService.getTeamMembers(shareteamids);
						resultList.addAll(userList);
					}
				}
				if (paraMap.containsKey("qry_shareusercodes")) {
					if (!StringUtil.isEmpty(shareusercodes)) {
						String tempuserCodes = "";
						String[] users = shareusercodes.split(",");
						for (String code : users) {
							tempuserCodes = tempuserCodes + "'" + code + "'" + ",";
						}
						if (tempuserCodes.length() > 0) {
							tempuserCodes = tempuserCodes.substring(0, tempuserCodes.length() - 1);
						}
						StringBufferProxy sql1 = new StringBufferProxy();
						sql1.appendSingle("select code as usercode, name as username from CboUser where code in ({0})",
								tempuserCodes);
						List<Map<String, Object>> userList = this.service.selectExecute(sql1.toString());
						resultList.addAll(userList);
					}
				}
				List<String> userCodeList = resultList.stream()
						.map(userMap -> ConvertUtil.convertToString(userMap.get("usercode"))).distinct()
						.collect(Collectors.toList());
				selectUserCodes = String.join(",", userCodeList);
			}
			// 通過用戶code查詢用戶
			StringBufferProxy sqlTemp = new StringBufferProxy();
			if (selectUserCodes != null) {
				String[] userCodeArray = selectUserCodes.split(",");
				if (userCodeArray != null && userCodeArray.length > 0) {
					List<String> userlist = new ArrayList<String>();
					String userCodeString = "";
					for (int i = 0; i < userCodeArray.length; i = i + 1) {
						if (i != 0 && i % 1000 == 0) {
							userCodeString = userCodeString.substring(0, userCodeString.length() - 1);
							userlist.add(userCodeString);
							userCodeString = "";
						} else {
							userCodeString += "'" + userCodeArray[i] + "'" + ",";
						}

					}
					if (!StringUtil.isEmpty(userCodeString)) {
						userCodeString = userCodeString.substring(0, userCodeString.length() - 1);
						userlist.add(userCodeString);
					}
					for (int i = 0; i < userlist.size(); i++) {
						if (i == 0) {
							sqlTemp.appendSingle(" code in ({0})", userlist.get(i));
						} else {
							sqlTemp.appendSingle(" or code in ({0})", userlist.get(i));
						}
					}
				}
			}
			sql.clear();
			sql.appendSingle("1=1");
			if (!StringUtil.isEmpty(sqlTemp.toString())) {
				sql.appendSingle(" and ({0} )", sqlTemp.toString());
			}
			if (paraMap.containsKey("qry_code")) {
				String code = ConvertUtil.convertToString(paraMap.get("qry_code"));
				if (code != null) {
					sql.appendSingle(" and code like '%{0}%' ", code);
				}
			}
			if (paraMap.containsKey("qry_name")) {
				String name = ConvertUtil.convertToString(paraMap.get("qry_name"));
				if (name != null) {
					sql.appendSingle(" and name like '{0}%' ", name);
				}
			}
			int totalCount = cboUserService.getCount(sql.toString());
			List<Map<String, Object>> tempList = null;
			if (query.getPageSize() > 0) {
				tempList = cboUserService.queryMapForPage(sql.toString(), query.getCurrentPage(), query.getPageSize(),
						query.getSidx(), query.getSord());
			} else
				tempList = cboUserService.queryMapByWhere(sql.toString());
			cboUserService.setDispFields(tempList);
			Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
			return ResponseResult.ok(page);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}
}
